﻿using System.Windows;
using System.Windows.Media;
using WickedFlame.Core.Shapes;

namespace WickedFlame.Core.Layers
{
    public class TopLayer : Layer
    {
        SelectionTrackerVisual selectionTrackerVisual;
        
        public TopLayer()
            : base()
        {
            this.Loaded += new RoutedEventHandler(OnLoaded);
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            selectionTrackerVisual = new SelectionTrackerVisual();
            AddShape(selectionTrackerVisual);
        }

        public void DrawTrackers(DrawingCanvas canvas)
        {
            //calls can come before the inizialisation!
            if (selectionTrackerVisual != null)
                selectionTrackerVisual.DrawTrackers(canvas);
        }

        public override void SetClipSize()
        {
            //do not set any clip size for the top layer so that the trackers can be drawn over the canvas border
            //base.SetClipSize();
        }
    }

    internal class SelectionTrackerVisual : DrawableShape
    {
        public SelectionTrackerVisual()
            : base()
        {
        }

        public override void Draw(DrawingContext drawingContext)
        {
        }

        public void DrawTrackers(DrawingCanvas canvas)
        {
            DrawingContext drawingContext = this.RenderOpen();

            double sc = canvas.Zoom;
            double scale = sc / 100;

            foreach (VectorShape shape in canvas.SelectedLayer.ShapeList.Selection)
            {
                shape.DrawTracker(drawingContext, scale);
            }

            // draw a rectangle that surounds everything
            if (canvas.SelectedLayer.ShapeList.SelectionCount > 1)
            {
                double x = canvas.Width;
                double y = canvas.Height;
                double bottom = 0;
                double right = 0;

                foreach (VectorShape s in canvas.SelectedLayer.ShapeList.Selection)
                {
                    if (s.Bounds.X < x)
                        x = s.Bounds.X;
                    if (s.Bounds.Y < y)
                        y = s.Bounds.Y;
                    if (s.Bounds.Right > right)
                        right = s.Bounds.Right;
                    if (s.Bounds.Bottom > bottom)
                        bottom = s.Bounds.Bottom;
                }

                Rect bounds = new Rect(x, y, right - x, bottom - y);

                drawingContext.DrawRectangle(null, new Pen(Brushes.Red, 1), bounds);
            }

            drawingContext.Close();
        }
    }
}
